package com.huanf.handle;

import com.huanf.enums.SystemEnum;
import com.huanf.exception.SystemException;
import com.plexpt.chatgpt.listener.AbstractStreamListener;
import com.plexpt.chatgpt.util.SseHelper;

import okhttp3.sse.EventSource;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import lombok.RequiredArgsConstructor;

/**
 * sse 流输出的规则。也可以用官方提供的SseStreamListener。我这里重写SseStreamListener主要是官方那个不会主动关闭流
 */
@RequiredArgsConstructor
public class SseStreamListener extends AbstractStreamListener {

    final SseEmitter sseEmitter;


    @Override
    public void onMsg(String message) {
        SseHelper.send(sseEmitter, message);
    }

    @Override
    public void onClosed(EventSource eventSource) {
        // 主动关闭流。回答完之后，就关闭流，这样前端就不会一直转圈了
        sseEmitter.complete();
    }

    @Override
    public void onError(Throwable throwable, String response) {
        SseHelper.complete(sseEmitter);
        throw new RuntimeException("官方那边的负载已饱和，请稍后再试");
    }

}